<?php

namespace Application\model;

use Cola\Exception\DbException;
use Cola\Model;
use Cola\Request;

/**
 * 充值基础参数处理
 * 当下面的参数与请求参数不同名时，就需要在子类的initPayParams方法中对其进行赋值
 * @property string $cpid 子包id
 * @property string $ccid 渠道子渠道id
 * @property string $shopId 商品id
 * @property string $orderId 订单号
 * @property string $account 用户帐号ID：用户认证的唯一标识
 * @property string $openId 平台原始账号
 * @property string $amount 人民币金额
 * @property string $sid 区服id
 * @property string $actorId 商品id
 * @property string $actorName 角色id
 * @property string $level 角色等级
 * @property string $vip 角色vip等级
 * @property string $ext2 服务端透传参数
 */
abstract class BaseOrderModel extends Model
{
    /**
     * 自动设置map
     * @var array
     */
    protected $auto_set_map = [];

    public $table = 'log_order';

    protected $actorCreateTime='';
    protected function _init(){
        $this->logfile('################# ' . PFORM_NAME . ' order start ################');
        $this->logfile("order params: " . json_encode(Request::param()));
    }


    public function get($k)
    {
        return Request::param($k);
    }

    public function initPayCallBack()
    {
        $this->autoSet();
        $this->initPayParams();
        $this->initCheckPayAmount();
        // 获取角色信息
        /* @var AccountModel $AccountModel */
        $AccountModel = $this->model('Account');
        $accountInfo = $AccountModel->getAccountInfo($this->account, $this->sid, $this->actorId);
        if(empty($accountInfo) || $accountInfo['status'] == 0){
            $this->logfile('role null');
            return 'role null';
        }
        /*if ($accountInfo['ccid'] != $this->ccid){
            $this->logfile("account and ccid error, account:{$this->account},actorId:{$this->actorId}, ccid:{$this->ccid}, data ccid:{$accountInfo['ccid']}");
            return 'account invalid';
        }*/
        $this->logfile('checked account');
        $this->actorCreateTime = $accountInfo['create_time'];
        return false;
    }

    public function initCheckPayAmount($return = false)
    {
        try{
            $ReportModel = $this->model("Report");
            $commond = $ReportModel->checkNotify('pay_amount');
            if($commond && $commond['status']){
                if($return){
                    return $commond['ext1'];
                }
                $this->amount =  $commond['ext1'];

            }
        }catch (\PDOException $exception){

        }

    }

    public function getOrderByOrderId($account, $orderId,$cid = '')
    {
        !$cid && $cid = realCID();
        $sql = "select * from log_order where orderid = '{$orderId}' and account = '{$account}' and cid = '{$cid}'";
        $orderInfo = $this->db('_logdb')->row($sql);
        return $orderInfo;
    }

    /**
     * 保存订单
     * @param $config
     * @return array|bool|\PDOStatement|null
     * @throws DbException
     */
    public function saveOrder($config)
    {
        //默认平台model没处理
        $this->orderId = empty($this->orderId) ? $this->cpid.$this->actorId.date('YmdHis').rand(1000, 9999) : $this->orderId;
        $data = [
            'cid' => CID,
            'cpid' => $this->cpid,
            'ccid' => $this->ccid,
            'sid' => $this->sid,
            'account' => $this->account,
            'actor_id' => $this->actorId,
            'actor_name' => $this->actorName,
            'level' => $this->level,
            'vip' => $this->vip ?? 0,
            'orderid' => $this->orderId,
            'recharge_id' => $config['id'],
            'recharge_name' => $config['describe'],
            'amount' => $this->amount,
            'param' => $this->ext2,
            'create_dt' => date('Y-m-d H:i:s'),
        ];
        $inserId = $this->db('_logdb')->insert($data, 'log_order');
        $this->logfile('saved order success, id:'.$inserId.' orderid:'.$this->orderId);
        if ($inserId > 0) {
            return $data;
        } else {
            $this->logfile('saved order fail, data:'.json_encode($data));
            return [];
        }
    }

    public function checkProduct(): array
    {
        /* @var \Application\model\BasePayModel $m */
        $m = $this->model('Pay');
        $config =$m->getRechargeConfig($this->shopId);
        if (empty($config)){
            $this->logfile("orderId:{$this->orderId} uid:{$this->role} shopId:{$this->shopId} invalid, config empty");
            return [];
        }
        $amount = $this->initCheckPayAmount(true);
        if($amount){
            $config['amount'] = $amount;
        }
        $this->logfile('checked product');
        return $config;
    }

    public function checkOpenPay(){
        $ChannelModel = new ChannelModel();
        $channel = $ChannelModel->getChannelInfo(CID);
        if($channel['is_open_pay'] ?? 0){
            return true;
        }
        return false;
    }
    public function successLog()
    {
        $this->logfile('################# test order end ##################');
    }

    /**
     * 根据配置自动匹配请求参数与项目字段
     * @return void
     */
    protected function autoSet()
    {
        foreach($this->auto_set_map as $field => $param)
        {
            $this->$field = $this->$param;
        }
    }

    public function __get($name = '')
    {
        if(in_array($name, ['db','cache','config','redis'])){
            return parent::__get($name);
        }
        return $this->$name = $this->get($name);
    }

    /**
     * 初始化支付回调参数
     * @return void
     */
    abstract protected function initPayParams();
}